package com.brkj.download;

import java.io.File;
import java.util.List;

import com.brkj.model.DS_Course;
import com.brkj.util.ConstAnts;
import com.dgl.sdk.util.FileCache;
import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalDb;

import com.brkj.main.R;
import com.brkj.util.ImgShow;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class DownloadingCourseActivity{

	protected ListView course;
	protected TextView noContent;
	protected Context context;
	private View view;
	private BroadcastReceiver br;
	protected TextView titleText;
	
	protected FinalDb course_db;
	protected List<DS_Course> courseSaveList;
	
	private CourseDownloader downLoader;
	
	private boolean isEdit = false;
	private CourseDLingAdapter courseAdapter;
	
    public DownloadingCourseActivity(View v, Context context) {

		this.context = context;
		this.view = v;
	}
	
    public void setIsEdit(boolean tag){
    	isEdit = tag;
    	if(courseAdapter != null){
    		courseAdapter.notifyDataSetInvalidated();
    	}
    }
    
    public boolean getIsEdit(){
    	return isEdit;
    }

    public void Start(TextView t1) {
		
		course_db = FinalDb.create(context,ConstAnts.BRKJ_DOWNLOAD_COURSE_DB);
		downLoader = CourseDownloader.Create(context);
		
		titleText = t1;
		
		course = (ListView) view.findViewById(R.id.course);
		noContent = (TextView) view.findViewById(R.id.noContent);
		FillContent();
		
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction("com.brkj.newdowanloadCourse");
		myIntentFilter.addAction("com.brkj.dowanloadCourseFinish");

		br = new BroadcastReceiver(){

			@Override
			public void onReceive(Context context, Intent intent) {
				FillContent();
			}
		};
		
		context.registerReceiver(br, myIntentFilter);
	}

	public void Stop(){
		context.unregisterReceiver(br);
	}
	
	protected void FillContent() {
		if(courseSaveList != null){
			courseSaveList.clear();
		}
		
		courseSaveList = 
				course_db.findAllByWhere(DS_Course.class," ifFinish="+CourseDLUnit.UN_FINSHED);

		if ((courseSaveList.size() > 0) ) { 
			courseAdapter = new CourseDLingAdapter(context, courseSaveList);
			 course.setAdapter(courseAdapter);
			 
			 course.setVisibility(View.VISIBLE);
			 noContent.setVisibility(View.GONE);
		}else{
			course.setVisibility(View.GONE);
			noContent.setVisibility(View.VISIBLE);
		}
		
		setTitleText();
	}
	
	private void setTitleText(){
		 if ((courseSaveList.size() > 0) ) {
			 titleText.setText("正在下载 ("+courseSaveList.size()+")");
		 }else{
			 titleText.setText("正在下载 (0)");
		 }
		
	}
	public class CourseDLingAdapter extends BaseAdapter{
		private ListItemView listItemView;
		protected LayoutInflater listContainer; 
		private Context context;
		private List<DS_Course> courseList;
		private FinalBitmap fb;
		
		public CourseDLingAdapter(Context context, List<DS_Course> courseList){
			this.context = context;
			this.courseList = courseList;
			
			listContainer = LayoutInflater.from(context);
			fb = FinalBitmap.create(context);
		}
		
		private  class ListItemView{
			public ImageView CourseImg;
			public TextView Title;
			public ProgressBar progressBar;
			public TextView percent;
			public TextView runText;
			public View downloadView;
			public ImageView download;
			public Button delete;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return courseList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public void remove(int position) {
			courseList.remove(position);
			notifyDataSetChanged();
			
			if(getCount() == 0){
				course.setVisibility(View.GONE);
				noContent.setVisibility(View.VISIBLE);
			}
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			// 自定义视图
			listItemView = new ListItemView();
			// 获取list_item布局文件的视图
			if (convertView == null) {
				convertView = listContainer.inflate(R.layout.course_downloding_item, null);
				// 获取控件对象
				listItemView.CourseImg = (ImageView) convertView.findViewById(R.id.CourseImg);
				listItemView.Title = (TextView) convertView
						.findViewById(R.id.Title);
				listItemView.progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
				listItemView.percent = (TextView) convertView.findViewById(R.id.percent);
				listItemView.runText = (TextView) convertView.findViewById(R.id.runText);
				listItemView.download = (ImageView) convertView.findViewById(R.id.download);
				listItemView.downloadView = (View) convertView.findViewById(R.id.downloadView);
				listItemView.delete = (Button) convertView.findViewById(R.id.delete);
				
				// 设置控件集到convertView
				convertView.setTag(listItemView);
			} else {
				listItemView = (ListItemView) convertView.getTag();
			}
			
			if(getIsEdit()){
				listItemView.delete.setVisibility(View.VISIBLE);
			}else{
				listItemView.delete.setVisibility(View.GONE);
			}
			
			ImgShow.display(listItemView.CourseImg, courseList.get(position).getCourseImg());
			
			listItemView.Title.setText(courseList.get(position).getTitle());
			
			int courseID = courseList.get(position).getCourseID();
			downLoader.SetDownloadingView(courseID, listItemView.percent);
			listItemView.progressBar.setMax(100);
			
			boolean state = downLoader.getDLState(courseID);
			listItemView.downloadView.setOnClickListener(
					new myClickListener(courseID,state,listItemView.percent, listItemView.download, listItemView.runText));
			
			if(state){
				listItemView.download.setBackgroundResource(R.drawable.xiazaizk_pause);
				listItemView.runText.setText("暂停");
			}else{
				listItemView.download.setBackgroundResource(R.drawable.xiazaizk_down);
				listItemView.runText.setText("下载");
			}

            listItemView.percent.setText((String)courseList.get(position).getPercent() + "%");
			listItemView.percent.addTextChangedListener(new myTextWatcher(listItemView.progressBar, position));

			int progress = Integer.valueOf((String)courseList.get(position).getPercent()); 
			listItemView.progressBar.setProgress(progress);
			
			listItemView.delete.setTag(R.id.tag_first, courseList.get(position));
			listItemView.delete.setTag(R.id.tag_second, position);
			listItemView.delete.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					downLoader.PauseDownload(((DS_Course)arg0.getTag(R.id.tag_first)).getCourseID());
					downLoader.DeleteDowlod(((DS_Course)arg0.getTag(R.id.tag_first)).getCourseID());
					deleteCourse((DS_Course)arg0.getTag(R.id.tag_first));
					remove((Integer)arg0.getTag(R.id.tag_second));
					setTitleText();
				}

			});
			
			
			return convertView;
		}

		protected void deleteCourse(DS_Course course) {
			course_db.delete(course);
			
			String url = course.getVideoAdress();
			if((url==null) || (url.equals(""))){
				return;
			}
			
			try {
				FileCache fileCache = new FileCache(context, ConstAnts.DOWNLOAD_COURSE__DIR);
				File file = new File(fileCache.getAbsolutePathByUrl(url) + ".dltmp");
			    if (file.isFile() && file.exists()) {  
			        file.delete();  
			    }  
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		class myTextWatcher implements TextWatcher{
			private ProgressBar progressBar;
			private int position;
			public myTextWatcher(ProgressBar pg,  int position){
				progressBar = pg;
				this.position = position;
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				String str = s.toString();
				int progress = Integer.valueOf(str.substring(0, str.length()-1));  //去除百分号
				
				progressBar.setProgress(progress);
				
				if(courseList.size() > position){
					courseList.get(position).setPercent(str.substring(0, str.length()-1));
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
			
		}
		
		class myClickListener implements OnClickListener{
			int courseID;
			boolean state = false;
			TextView progressView;
			TextView runText;
			View btnView;
			
			public myClickListener(int courseID, boolean state, TextView progressView, View btnView, TextView runText){
				this.courseID = courseID;
				this.state = state;
				this.progressView = progressView;
				this.runText = runText;
				this.btnView = btnView;
			}
			@Override
			public void onClick(View v) {
				if(state){
					downLoader.PauseDownload(courseID);
					Intent intent = new Intent();
					intent.setAction("com.brkj.pauseDownload");
					context.sendBroadcast(intent);
				}else{
					downLoader.StartDownload(courseID, progressView);
				}
				
				state = !state;
				
				if(state){
					btnView.setBackgroundResource(R.drawable.xiazaizk_pause);
					runText.setText("暂停");
				}else{
					btnView.setBackgroundResource(R.drawable.xiazaizk_down);
					runText.setText("下载");
				}
			}
		};
	}



}

